import log from "./logger";
import settings from "./settings";
import {send} from "./metric";
import * as fs from 'fs';
import {spawnSync} from "child_process";
import {NodeCO, TrainAllCO} from "./interface";

function formatDate(date: Date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    const seconds = date.getSeconds().toString().padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

function sync(sourcePath: string, targetPath: string) {
    try {
        // 检查目标文件是否存在
        if (!fs.existsSync(targetPath)) {
            log.info(`文件不存在，开始复制文件：${sourcePath} to ${targetPath}`);
            fs.copyFileSync(sourcePath, targetPath);
            log.info(`复制文件完成`);
        } else {
            // 目标文件存在，比较最后修改时间
            const sourceStats = fs.statSync(sourcePath);
            const targetStats = fs.statSync(targetPath);
            log.info(`sourceStats.mtimeMs:${formatDate(sourceStats.mtime)}, targetStats.mtimeMs:${formatDate(targetStats.mtime)}`);
            if (sourceStats.mtimeMs !== targetStats.mtimeMs) {
                // 最后修改时间不同，执行复制命令
                log.info(`开始复制文件：${sourcePath} to ${targetPath}`);
                fs.copyFileSync(sourcePath, targetPath);
                log.info(`复制文件完成`);
            } else {
                // 最后修改时间相同，不执行任何操作
                log.info(`文件未修改，不需要复制：${sourcePath} to ${targetPath}`);
            }
        }
    } catch (e) {
        log.error(e)
    }
}

class ZhangziTrainWorker {
    init() {
        this.collection();
        // setInterval(() => {
        //     this.collection();
        // }, 1000 * 60)
    }

    async collection() {
        try {
            // 查看数据库是否有改变，update时间？hash？和现在的做比较，如果不一样则复制；
            // 源文件和目标文件的路径
            const sourcePath12 = '\\\\192.168.1.12\\tmhczcz\\Train.FDB';
            const targetPath12 = 'D:\\tmhczcz12\\Train.FDB';

            // log.info(`开始复制文件：${sourcePath12} to ${targetPath12}`);
            // fs.copyFileSync(sourcePath12, targetPath12);
            // log.info(`复制文件完成`);

            log.info("开始执行数据采集，数据库路径：", targetPath12);
            const cmd1 = spawnSync('C:\\Users\\HUAWEI\\source\\repos\\firebirdReader\\firebirdReader\\bin\\x86\\Debug\\net8.0\\firebirdReader.exe', ["1"], {encoding: 'utf8'});
            if (cmd1.stdout) {
                // log.info('输出结果:', cmd1.stdout);
                // 使用正则表达式来匹配不同的换行符
                const lines = cmd1.stdout.split(/\r?\n/);
                const nodes: NodeCO[] = []
                for (let i = 1; i < lines.length - 1; i++) {
                    const data = lines[i].split("|");
                    // log.info(data);
                    nodes.push({
                        diffWeight: Number.parseFloat(data[9]),
                        code: data[1],
                        lable: null,
                        maxNetWeight: Number.parseFloat(data[7]),
                        no: data[6],
                        sort: Number.parseInt(data[4]),
                        speed: null,
                        standardTareWeight: null,
                        time: data[11],
                        trainCode: lines[0].split("|")[1],
                        carType: data[5],
                        weight: Number.parseFloat(data[8]),
                        containerNumber1: null,
                        containerNumber2: null,
                        containerType1: null,
                        containerType2: null,
                        state: 'Done'
                    })
                }
                // 处理时间
                const ccsj = lines[0].split("|")[3];
                let start = lines[0].split("|")[4].trim();
                let end = lines[0].split("|")[5].trim();
                if (start !== "") {
                    start = ccsj + " " + start;
                }
                if (end !== "") {
                    end = ccsj + " " + end;
                }

                const trainCO: TrainAllCO = {
                    boxCount: 0,
                    code: lines[0].split("|")[1],
                    deviceName: settings.name,
                    direction: "leave",
                    endTime: end,
                    firstNo: nodes[0].no,
                    lastNo: nodes[nodes.length - 1].no,
                    name: lines[0].split("|")[2],
                    no: lines[0].split("|")[2],
                    nodes: nodes,
                    platformId: settings.platformId,
                    platformName: settings.platformName,
                    productName: lines[0].split("|")[10],
                    senderName: lines[1].split("|")[2],
                    startTime: start,
                    stationName: lines[1].split("|")[3],
                    time: lines[0].split("|")[11],
                    totalDiffWeight: Number.parseFloat(lines[0].split("|")[9]),
                    totalMaxWeight: Number.parseFloat(lines[0].split("|")[7]),
                    totalNode: Number.parseInt(lines[0].split("|")[6]),
                    totalWeight: Number.parseFloat(lines[0].split("|")[8]),
                    type: "db",
                    wagonType: "Gondola"
                };
                log.info("trainCO:", trainCO);
            }

            // const cmd1 = spawn('C:\\Users\\HUAWEI\\source\\repos\\firebirdReader\\firebirdReader\\bin\\x86\\Debug\\net8.0\\firebirdReader.exe', ["1"]);
            // cmd1.stdout.setEncoding("utf8");
            // cmd1.stdout.on('data', function (data) {
            //     log.info('输出结果: ' + data);
            // });

            // 查看数据库是否有改变，update时间？hash？和现在的做比较，如果不一样则复制；
            // 源文件和目标文件的路径
            const sourcePath22 = '\\\\192.168.1.22\\tmhczcz\\Train.FDB';
            const targetPath22 = 'D:\\tmhczcz22\\Train.FDB';
            // log.info(`开始复制文件：${sourcePath22} to ${targetPath22}`);
            // fs.copyFileSync(sourcePath22, targetPath22);
            // log.info(`复制文件完成`);
            // log.info("开始执行数据采集，数据库路径：", targetPath22);
            // const cmd2 = spawn('C:\\Users\\HUAWEI\\source\\repos\\firebirdReader\\firebirdReader\\bin\\x86\\Debug\\net8.0\\firebirdReader.exe', ["2"]);
            // cmd2.stdout.setEncoding("utf8");
            // cmd2.stdout.on('data', function (data) {
            //     log.info('输出结果: ' + data);
            // });
        } catch (e) {
            log.error(e)
        }
        // 延时1分钟循环调用
        setTimeout(() => {
            log.info("延时时间到，开始新的采集")
            this.collection();
        }, 1000 * 60 * 5)
    }
}

const zhangziTrainWorker = new ZhangziTrainWorker();
export default zhangziTrainWorker;